package com.example.othree.controller;

import com.example.othree.common.R;

import com.example.othree.common.StaionNameNumber;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.*;
import org.json.simple.JSONObject;

@RestController
@CrossOrigin
@RequestMapping("/api")
public class ReadM3Controller {

    @Autowired
    StaionNameNumber staionNameNumber;

    // 文件上传的保存路径
    @Value("${data.filePath}")
    private String filePath;

    @GetMapping("/readFile/everyTime")
    @ApiOperation("返回指定城市（邢台、衡水）所有站点的O3、PM10、PM2.5等污染物的逐时浓度预报结果。")
    public R readFileEveryTime(@RequestParam("城市") String city,
                               @RequestParam("日期") String date,
                               @RequestParam("起报时刻") String startTime,
                               @RequestParam("时刻") String time,
                               @RequestParam("要素") String element,
                               @RequestParam("数据类型") String type) {
        String year = date.substring(0, 4);
        String directoryPath = filePath+"//hour//"+year+"//"+date+"//"+element+"_VALUE"; //根据要素选择文件夹

        List<String> list = new ArrayList<>();
        File dir = new File(directoryPath);
        // 需要提取的 number 值
        List<String> stationNumbers = getNumbersByCity(city);
        //文件名
        String regex = String.format("%s%s.%s", date,startTime, time);
        System.out.println(directoryPath);
        System.out.println(regex);

        //找到对应的文件
        File[] files = dir.listFiles((dir1, name) -> {
            return name.matches(regex);
        });

        if (files != null) {
            for (File file : files) {
                // 读取每个文件并跳过前三行
                List<String> fileData = readFileSkippingFirstThreeLines(file);
                //读取文件中全部数据
                list.addAll(fileData);
            }
        }
        System.out.println(list);

        List<JSONObject> result = findDataByNumbers(list, stationNumbers,city);

        return R.ok().data("data", result);
    }

    @GetMapping("/readFile/everyday")
    @ApiOperation("返回指定城市（邢台、衡水）所有站点的O3、PM10、PM2.5等污染物的逐日浓度预报结果。")
    public R readFileEveryday(@RequestParam("城市") String city,
                               @RequestParam("日期") String date,
                               @RequestParam("时刻") String time,
                               @RequestParam("起报时刻") String startTime,
                               @RequestParam("结束预报时刻") String endTime,
                               @RequestParam("要素") String element,
                               @RequestParam("数据类型") String type) {
        List<String> list = new ArrayList<>();

        if(Objects.equals(element, "O3")){
            list = O3EverydayResult(date,time,startTime,endTime,city,element,filePath);
        }else if(Objects.equals(element, "PM10")){
            list = extractAverageValues(date,time,startTime,endTime,city,element,filePath);
        }else if(Objects.equals(element, "PM25")){
            list = extractAverageValues(date,time,startTime,endTime,city,element,filePath);
        }

        // 需要提取的 number 值
        List<String> stationNumbers = getNumbersByCity(city);

        List<JSONObject> result = findDataByNumbers(list, stationNumbers,city);

        return R.ok().data("data", result);
    }

    @GetMapping("/readFile/stationForecast")
    @ApiOperation("返回指定站点在未来多日的污染物浓度逐时or逐日预报结果。")
    public R stationForecast(@RequestParam("站点名") String stationName,
                             @RequestParam("日期") String date,
                             @RequestParam("起报时刻") String startTime,
                             @RequestParam("预报天数") int day,
                             @RequestParam("要素") String element,
                             @RequestParam("预报精度") String accuracy){

        JSONObject result = new JSONObject();
        String stationNumber = staionNameNumber.getNumber(stationName);
        if (Objects.equals(accuracy, "hour")) {
            result =forecastBytime(filePath,stationNumber,stationName,date,startTime,element,day,accuracy);
        }else if(Objects.equals(accuracy, "day")){
            result = forecastByDay(filePath,stationNumber,stationName,date,startTime,element,day,accuracy);
        }

        return R.ok().data("data", result);
    }

    public static  JSONObject forecastBytime(String filePath,String stationNumber,String stationName,String date,String startTime,String element, int day,String accuracy){
        List<String> list = new ArrayList<>();
        String year = date.substring(0, 4);
        String directoryPath = filePath+"//"+accuracy+"//"+year+"//"+date+"//"+element+"_VALUE";
        File dir = new File(directoryPath);
//        int date_num = Integer.parseInt(date);
        JSONObject object = new JSONObject();
        JSONObject result = new JSONObject();
        JSONObject dayAllTime = new JSONObject();

        if(day == 1){
            for(int j=1;j <= 17;j++) {
                String formatted = String.format("%03d", j);
                String regex = String.format("%s%s.%s", date, startTime, formatted);
                File[] files = dir.listFiles((dir1, name) -> {
                    return name.matches(regex);
                });
                if (files != null) {
                    for (File file : files) {
                        List<String> fileData = readFileSkippingFirstThreeLines(file);
                        list.addAll(fileData);
                    }
                }
                String forecastResult = "";
                for (String line : list) {
                    String[] parts = line.split("\\s+"); // 分割字符串，以空格为分隔符

                    if (parts[0].equals(stationNumber)) {
                        forecastResult = parts[4];
                    }
                }
                dayAllTime.put(formatted,forecastResult);
            }
        }else {
            for (int i = 1; i <= day * 24; i++) {

                String formatted = String.format("%03d", i);
                String regex = String.format("%s%s.%s", date, startTime, formatted);
                File[] files = dir.listFiles((dir1, name) -> {
                    return name.matches(regex);
                });
                if (files != null) {
                    for (File file : files) {
                        List<String> fileData = readFileSkippingFirstThreeLines(file);
                        list.addAll(fileData);
                    }
                }
                String forecastResult = "";
                for (String line : list) {
                    String[] parts = line.split("\\s+"); // 分割字符串，以空格为分隔符

                    if (parts[0].equals(stationNumber)) {
                        forecastResult = parts[4];
                    }
                }
                dayAllTime.put(formatted, forecastResult);
            }
        }
        object.put(date,dayAllTime);
        result.put(stationName,object);
        System.out.println(result);

        return result;
    }

    public static  JSONObject forecastByDay(String filePath,String stationNumber,String stationName,String date,String startTime,String element, int day, String accuracy){
        String year = date.substring(0, 4);
        String directoryPath = filePath+"//"+accuracy+"//"+year+"//"+date+"//"+element+"_VALUE";
        System.out.println(directoryPath);
        File dir = new File(directoryPath);
        //int date_num = Integer.parseInt(date);
        List<String> dateRange = generateDateRange(date, day);
        JSONObject object = new JSONObject();
        JSONObject result = new JSONObject();
//        File[] files = dir.listFiles();
        for( int i =1; i <= day; i++){
            String formatted = String.format("%03d", i*24);
            String regex = String.format("%s%s.%s", date, startTime, formatted);
            List<String> list = new ArrayList<>();
            File[] files = dir.listFiles((dir1, name) -> {
                return name.matches(regex);
            });
            if (files != null) {
                for (File file : files) {
                    List<String> fileData = readFileSkippingFirstThreeLines(file);
                    list.addAll(fileData);
                }
            }else{
                result.put("error","文件不存在！！！！");
            }
            double forecastEverytime = 0;
            for (String line : list) {
                String[] parts = line.split("\\s+");
                String firstColumn = parts[0];  // 获取第一列
                System.out.println(firstColumn);
                if (firstColumn.equals(stationNumber)) {
                    forecastEverytime = new Double(parts[4]);// 找到匹配的行，得到预报结果
                    System.out.println(forecastEverytime);
                }
            }
            String date_num = dateRange.get(i-1);
            object.put(date_num,forecastEverytime);
        }
        result.put(stationName,object);
//        if(element.equals("PM25")||element.equals("PM10")){
//            result = forecastByDayPM(dir,stationNumber,stationName,date,startTime,day);
//        }else if(element.equals("O3")){
//            result = forecastByDayO3(dir,stationNumber,stationName,date,startTime,day);
//        }
        return result;
    }

    public static List<String> generateDateRange(String startDate, int days) {
        // 参数校验
        if (startDate == null || startDate.length() != 8 || days < 1 || days > 10) {
            throw new IllegalArgumentException("Invalid input parameters");
        }

        List<String> dateList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        try {
            // 解析起始日期
            LocalDate date = LocalDate.parse(startDate, formatter);

            // 生成日期范围
            for (int i = 0; i < days; i++) {
                dateList.add(date.format(formatter));
                date = date.plusDays(1);
            }

        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid date format: " + startDate, e);
        }
        return dateList;
    }



//    public static JSONObject forecastByDayO3(File dir,String stationNumber,String stationName,String date,String startTime, int day){
//        JSONObject object = new JSONObject();
//        JSONObject result = new JSONObject();
//        File[] files = dir.listFiles();
//        int date_num = Integer.parseInt(date) -1 ;
//
//        if(startTime.equals("08")) {
//            for (int i = 0; i<=day*24 -1; i+=24) {
//                date_num += 1;
//                List<Double> avg = new ArrayList<>();//存放平均值
//                int m=0;
//                for (int j = i; j <= i+16; j ++) {
//
//                    double forecastEverytimeAll = 0.00;
//                    for (int p = 0; p < 8; p++) {
//                        List<String> list = new ArrayList<>();
//                        String formatted = String.format("%03d", p + j);
//                        String regex = String.format("%s%s.%s", date, startTime, formatted);
//                        files = dir.listFiles((dir1, name) -> {
//                            return name.matches(regex);
//                        });
//                        if (files != null) {
//                            for (File file : files) {
//                                List<String> fileData = readFileSkippingFirstThreeLines(file);
//                                list.addAll(fileData);
//                            }
//                        } else {
//                            throw new IllegalArgumentException("file is null");
//                        }
//
//                        for (String line : list) {
//                            // 分割字符串，以空格为分隔符
//                            String[] parts = line.split(" ");
//                            String firstColumn = parts[0];  // 获取第一列
//                            if (firstColumn.equals(stationNumber)) {
//                                double forecastEverytime = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                                forecastEverytimeAll += forecastEverytime;//将预报结果加和
//                            }
//                        }
//                    }
//                    double forecastEverytime = forecastEverytimeAll / 8;//求出平均值
//                    avg.add(m, forecastEverytime);
//                    m+=1;
//                }
//                double max = avg.stream().max(Double::compare)  // 找到最大值
//                        .orElse(Double.NEGATIVE_INFINITY); // 获取最大值并转换为 double
//                String formattedValue = String.format("%.2f", max);
//                System.out.println(formattedValue);
//                object.put(date_num, formattedValue);
//                result.put(stationName, object);
//            }
//        }else if(startTime.equals("20")) {
//            date_num += 1;
//            if(day <= 9) {
//                for (int i = 12; i <= day * 24 + 11; i += 24) {
//                    date_num += 1;
//                    List<Double> avg = new ArrayList<>();//存放平均值
//                    int m = 0;
//                    for (int j = i; j <= i + 16; j++) {
//
//                        double forecastEverytimeAll = 0.00;
//                        for (int p = 0; p < 8; p++) {
//                            List<String> list = new ArrayList<>();
//                            String formatted = String.format("%03d", p + j);
//                            String regex = String.format("%s%s.%s", date, startTime, formatted);
//                            files = dir.listFiles((dir1, name) -> {
//                                return name.matches(regex);
//                            });
//                            if (files != null) {
//                                for (File file : files) {
//                                    List<String> fileData = readFileSkippingFirstThreeLines(file);
//                                    list.addAll(fileData);
//                                }
//                            } else {
//                                throw new IllegalArgumentException("file is null");
//                            }
//
//                            for (String line : list) {
//                                // 分割字符串，以空格为分隔符
//                                String[] parts = line.split(" ");
//                                String firstColumn = parts[0];  // 获取第一列
//                                if (firstColumn.equals(stationNumber)) {
//                                    double forecastEverytime = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                                    forecastEverytimeAll += forecastEverytime;//将预报结果加和
//                                }
//                            }
//                        }
//                        double forecastEverytime = forecastEverytimeAll / 8;//求出平均值
//                        avg.add(m, forecastEverytime);
//                        m += 1;
//                    }
//                    double max = avg.stream().max(Double::compare)  // 找到最大值
//                            .orElse(Double.NEGATIVE_INFINITY); // 获取最大值并转换为 double
//                    String formattedValue = String.format("%.2f", max);
//                    System.out.println(formattedValue);
//                    object.put(date_num, formattedValue);
//                }
//            } else if (day == 10) {
//                for (int i = 12; i <= (day-1) * 24 + 11; i += 24) {
//                    date_num += 1;
//                    List<Double> avg = new ArrayList<>();//存放平均值
//                    int m = 0;
//                    for (int j = i; j <= i + 16; j++) {
//
//                        double forecastEverytimeAll = 0.00;
//                        for (int p = 0; p < 8; p++) {
//                            List<String> list = new ArrayList<>();
//                            String formatted = String.format("%03d", p + j);
//                            String regex = String.format("%s%s.%s", date, startTime, formatted);
//                            files = dir.listFiles((dir1, name) -> {
//                                return name.matches(regex);
//                            });
//                            if (files != null) {
//                                for (File file : files) {
//                                    List<String> fileData = readFileSkippingFirstThreeLines(file);
//                                    list.addAll(fileData);
//                                }
//                            } else {
//                                throw new IllegalArgumentException("file is null");
//                            }
//
//                            for (String line : list) {
//                                // 分割字符串，以空格为分隔符
//                                String[] parts = line.split(" ");
//                                String firstColumn = parts[0];  // 获取第一列
//                                if (firstColumn.equals(stationNumber)) {
//                                    double forecastEverytime = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                                    forecastEverytimeAll += forecastEverytime;//将预报结果加和
//                                }
//                            }
//                        }
//                        double forecastEverytime = forecastEverytimeAll / 8;//求出平均值
//                        avg.add(m, forecastEverytime);
//                        m += 1;
//                    }
//                    double max = avg.stream().max(Double::compare)  // 找到最大值
//                            .orElse(Double.NEGATIVE_INFINITY); // 获取最大值并转换为 double
//                    String formattedValue = String.format("%.2f", max);
//                    System.out.println(formattedValue);
//                    object.put(date_num, formattedValue);
//
//                }
//                List<Double> avg1 = new ArrayList<>();
//                int m1 = 0;
//                for(int i = 228; i <= 232; i ++) {
//                    double forecastEverytimeAll = 0.00;
//                    for (int p = 0; p < 8; p++) {
//                        List<String> list = new ArrayList<>();
//                        String formatted = String.format("%03d", p + i);
//                        String regex = String.format("%s%s.%s", date, startTime, formatted);
//                        files = dir.listFiles((dir1, name) -> {
//                            return name.matches(regex);
//                        });
//                        if (files != null) {
//                            for (File file : files) {
//                                List<String> fileData = readFileSkippingFirstThreeLines(file);
//                                list.addAll(fileData);
//                            }
//                        } else {
//                            throw new IllegalArgumentException("file is null");
//                        }
//
//                        for (String line : list) {
//                            // 分割字符串，以空格为分隔符
//                            String[] parts = line.split(" ");
//                            String firstColumn = parts[0];  // 获取第一列
//                            if (firstColumn.equals(stationNumber)) {
//                                double forecastEverytime = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                                forecastEverytimeAll += forecastEverytime;//将预报结果加和
//                            }
//                        }
//                    }
//                    double forecastEverytime = forecastEverytimeAll / 8;//求出平均值
//                    avg1.add(m1, forecastEverytime);
//                    m1 += 1;
//                }
//                double max1 = avg1.stream().max(Double::compare)  // 找到最大值
//                        .orElse(Double.NEGATIVE_INFINITY); // 获取最大值并转换为 double
//                String formattedValue = String.format("%.2f", max1);
//                object.put(date_num+10, formattedValue);
//                result.put(stationName, object);
//            }
//        }
//
//        return result;
//    }


//    public static JSONObject forecastByDayPM(File dir,String stationNumber,String stationName,String date,String startTime, int day){
//        JSONObject object = new JSONObject();
//        JSONObject result = new JSONObject();
//        int date_num = Integer.parseInt(date);
//        File[] files = dir.listFiles();
//        if(startTime.equals("08")){
//            List<String> list = new ArrayList<>();
//            if(day == 1){
//                String regex08 = String.format("%s%s.(000|001|002|003|004|005|006|007|008|009|010|011|012|013|014|015|016)", date, startTime);
//                files = dir.listFiles((dir1, name) -> {
//                    return name.matches(regex08);
//                });
//                if (files != null) {
//                    for (File file : files) {
//                        List<String> fileData = readFileSkippingFirstThreeLines(file);
//                        list.addAll(fileData);
//                    }
//                }else {
//                    throw new IllegalArgumentException("file is null");
//                }
//                double forecastEverytimeAll = 0.00;
//                for (String line : list) {
//                    // 分割字符串，以空格为分隔符
//                    String[] parts = line.split(" ");
//
//                    String firstColumn = parts[0];  // 获取第一列
//
//                    if (firstColumn.equals(stationNumber)) {
//                        double forecastEverytime = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                        forecastEverytimeAll += forecastEverytime;//将预报结果加和
//                    }
//                }
//                double forecastEverytime = forecastEverytimeAll/16;//求出平均值
//                String formattedValue = String.format("%.2f", forecastEverytime);//只保留小数点后两位并转化为String类型
//                object.put(date,formattedValue);
//            }else {
//                String regex08 = String.format("%s%s.(000|001|002|003|004|005|006|007|008|009|010|011|012|013|014|015|016)", date, startTime);
//                files = dir.listFiles((dir1, name) -> {
//                    return name.matches(regex08);
//                });
//                if (files != null) {
//                    for (File file : files) {
//                        List<String> fileData = readFileSkippingFirstThreeLines(file);
//                        list.addAll(fileData);
//                    }
//                }else {
//                    throw new IllegalArgumentException("file is null");
//                }
//                double forecastEverytimeAll1 = 0.00;
//                for (String line : list) {
//                    // 分割字符串，以空格为分隔符
//                    String[] parts = line.split(" ");
//
//                    String firstColumn = parts[0];  // 获取第一列
//
//                    if (firstColumn.equals(stationNumber)) {
//                        double forecastEverytime1 = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                        forecastEverytimeAll1 += forecastEverytime1;//将预报结果加和
//                    }
//                }
//                double forecastEverytime1 = forecastEverytimeAll1/16;//求出平均值
//                String formattedValue1 = String.format("%.2f", forecastEverytime1);//只保留小数点后两位并转化为String类型
//                object.put(date_num,formattedValue1);
//                for(int i = 17; i<=day*24 -8; i+=24){
//                    List<String> list2 = new ArrayList<>();
//                    date_num += 1;
//                    for(int j=0; j<24; j++){
//                        String formatted = String.format("%03d", i+j);
//                        String regex = String.format("%s%s.%s",date,startTime,formatted);
//                        files = dir.listFiles((dir1, name) -> {
//                            return name.matches(regex);
//                        });
//                        if (files != null) {
//                            for (File file : files) {
//                                List<String> fileData = readFileSkippingFirstThreeLines(file);
//                                list2.addAll(fileData);
//                            }
//                        }else {
//                            throw new IllegalArgumentException("file is null");
//                        }
//                    }
//                    double forecastEverytimeAll = 0.00;
//                    for (String line : list2) {
//                        // 分割字符串，以空格为分隔符
//                        String[] parts = line.split(" ");
//
//                        String firstColumn = parts[0];  // 获取第一列
//
//                        if (firstColumn.equals(stationNumber)) {
//                            double forecastEverytime = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                            forecastEverytimeAll += forecastEverytime;//将预报结果加和
//                        }
//                    }
//                    double forecastEverytime = forecastEverytimeAll/24;//求出平均值
//                    String formattedValue = String.format("%.2f", forecastEverytime);//只保留小数点后两位并转化为String类型
//                    object.put(date_num,formattedValue);
//                }
//            }
//            result.put(stationName,object);
//        }else if(startTime.equals("20")){
//            List<String> list = new ArrayList<>();
//            if(day <= 9) {
//                for (int i = 5; i <= day * 24 + 4; i += 24) {
//                    List<String> list2 = new ArrayList<>();
//                    date_num += 1;
//                    for (int j = 0; j < 24; j++) {
//                        String formatted = String.format("%03d", i + j);
//                        String regex = String.format("%s%s.%s", date, startTime, formatted);
//                        System.out.println(regex);
//                        files = dir.listFiles((dir1, name) -> {
//                            return name.matches(regex);
//                        });
//                        if (files != null) {
//                            for (File file : files) {
//                                List<String> fileData = readFileSkippingFirstThreeLines(file);
//                                list2.addAll(fileData);
//                            }
//                        } else {
//                            throw new IllegalArgumentException("file is null");
//                        }
//                    }
//                    double forecastEverytimeAll = 0.00;
//                    for (String line : list2) {
//                        // 分割字符串，以空格为分隔符
//                        String[] parts = line.split(" ");
//
//                        String firstColumn = parts[0];  // 获取第一列
//
//                        if (firstColumn.equals(stationNumber)) {
//                            double forecastEverytime = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                            forecastEverytimeAll += forecastEverytime;//将预报结果加和
//                        }
//                    }
//                    double forecastEverytime = forecastEverytimeAll / 24;//求出平均值
//                    String formattedValue = String.format("%.2f", forecastEverytime);//只保留小数点后两位并转化为String类型
//                    System.out.println(forecastEverytime);
//                    object.put(date_num, formattedValue);
//                }
//            }else{
//                for (int i = 5; i <= (day-1) * 24 + 4; i += 24) {
//                    List<String> list2 = new ArrayList<>();
//                    date_num += 1;
//                    for (int j = 0; j < 24; j++) {
//                        String formatted = String.format("%03d", i + j);
//                        String regex = String.format("%s%s.%s", date, startTime, formatted);
//                        files = dir.listFiles((dir1, name) -> {
//                            return name.matches(regex);
//                        });
//                        if (files != null) {
//                            for (File file : files) {
//                                List<String> fileData = readFileSkippingFirstThreeLines(file);
//                                list2.addAll(fileData);
//                            }
//                        } else {
//                            throw new IllegalArgumentException("file is null");
//                        }
//                    }
//                    double forecastEverytimeAll = 0.00;
//                    for (String line : list2) {
//                        // 分割字符串，以空格为分隔符
//                        String[] parts = line.split(" ");
//
//                        String firstColumn = parts[0];  // 获取第一列
//
//                        if (firstColumn.equals(stationNumber)) {
//                            double forecastEverytime = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                            forecastEverytimeAll += forecastEverytime;//将预报结果加和
//                        }
//                    }
//                    double forecastEverytime = forecastEverytimeAll / 24;//求出平均值
//                    String formattedValue = String.format("%.2f", forecastEverytime);//只保留小数点后两位并转化为String类型
//                    object.put(date_num, formattedValue);
//                }
//                String regex20 = String.format("%s%s.(221|222|223|224|225|226|227|228|229|230|231|232|233|234|235|236|237|238|239)", date, startTime);
//                files = dir.listFiles((dir1, name) -> {
//                    return name.matches(regex20);
//                });
//                if (files != null) {
//                    for (File file : files) {
//                        List<String> fileData = readFileSkippingFirstThreeLines(file);
//                        list.addAll(fileData);
//                    }
//                }else {
//                    throw new IllegalArgumentException("file is null");
//                }
//                double forecastEverytimeAll1 = 0.00;
//                for (String line : list) {
//                    // 分割字符串，以空格为分隔符
//                    String[] parts = line.split(" ");
//
//                    String firstColumn = parts[0];  // 获取第一列
//
//                    if (firstColumn.equals(stationNumber)) {
//                        double forecastEverytime1 = new Double(parts[4]);// 找到匹配的行，得到预报结果
//                        forecastEverytimeAll1 += forecastEverytime1;//将预报结果加和
//                    }
//                }
//                double forecastEverytime1 = forecastEverytimeAll1/19;//求出平均值
//                String formattedValue1 = String.format("%.2f", forecastEverytime1);//只保留小数点后两位并转化为String类型
//                object.put(date_num+10,formattedValue1);
//            }
//            result.put(stationName,object);
//        }
//
//        return result;
//    }


    /**
     * 根据 number 查找数据并返回 JSON 格式
     *
     * @param data         原始数据
     * @param targetNumbers 需要查找的 number
     * @param city 查找的城市
     * @return 匹配数据的 JSON 格式
     */
    public static List<JSONObject> findDataByNumbers(List<String> data, List<String> targetNumbers,String city) {
        List<JSONObject> resultList = new ArrayList<>();
        String[] stationNames = new String[targetNumbers.size()];
        if(Objects.equals(city, "邢台")) {
            String[] stationNames1 = {"沙河", "柏乡", "临城", "隆尧", "宁晋", "内丘", "邢台", "巨鹿", "任泽",
                    "南和", "广宗", "平乡", "新河", "南宫", "清河", "威县", "临西"};
            stationNames = stationNames1;
        }
        else if(Objects.equals(city,"衡水")) {
            String[] stationNames2 = {"饶阳", "深州", "安平", "武强",
                    "衡水", "武邑", "冀州", "故城", "枣强", "阜城", "景县"};
            stationNames = stationNames2;
        }else{
            throw new IllegalArgumentException("City error!");
        }

        for (String line : data) {
            // 按空格分割每一行
            String[] parts = line.split("\\s+");

            // 检查第一列数字是否在目标列表中
            if (targetNumbers.contains(parts[0])) {
                // 找到匹配的目标编号，确定其站点名称
                int index = targetNumbers.indexOf(parts[0]);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("stationName", stationNames[index]);  // 对应的站点名称
                jsonObject.put("lon", parts[1]);  // 经度
                jsonObject.put("lat", parts[2]);  // 纬度
                jsonObject.put("forecastResult", parts[4]);  // 结果值
                resultList.add(jsonObject);
            }
        }
        // 返回所有匹配的结果
        return resultList;
    }

    /**
     * 根据 city 获取该城市下的全部站点号并返回 List<String> 格式
     *
     * @param city 查找的城市
     * @return 匹配数据的 List<String>格式
     */
    private static List<String> getNumbersByCity(String city) {
        List<String> list = new ArrayList<>();
        if(Objects.equals(city, "邢台")){
            List<String> stationNumbers1 = Arrays.asList("53781", "53785", "53792", "53794", "53796", "53797", "53798", "53799",
                    "53883", "53891", "54631", "54632", "54633", "54705", "54706", "54800", "54801");
            list = stationNumbers1;
        } else if (Objects.equals(city, "衡水")) {
            List<String> stationNumbers2 = Arrays.asList("54606", "54608", "54609", "54700", "54702", "54703",
                    "54704", "54707", "54708", "54710", "54711");
            list = stationNumbers2;
        }
        return list;
    }

    // 读取文件并跳过前三行
    private static List<String> readFileSkippingFirstThreeLines(File file) {
        List<String> result = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            int lineCount = 0;

            // 读取文件内容，跳过前三行
            while ((line = reader.readLine()) != null) {
                lineCount++;
                if (lineCount > 3) {  // 跳过前三行
                    result.add(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    //计算臭氧8h滑动平均
    private static List<String> O3EverydayResult(String date, String time,String startTime,String endTime,String city ,String element, String filePath){
        String year = date.substring(0, 4);
        List<String> stationNumbers = getNumbersByCity(city);
        System.out.println(stationNumbers);
        String directoryPath = filePath+"//hour//"+year+"//"+date+"//"+element+"_VALUE";
        System.out.println(directoryPath);
        File dir = new File(directoryPath);
        String filename = date+time;
        System.out.println(filename);
        File[] files = dir.listFiles();
        List<String> re = new ArrayList<>();

        for(int j= Integer.parseInt(startTime); j <= Integer.parseInt(endTime)-7; j++) {

            List<String> resultString = new ArrayList<>();
            List<String> o3All = new ArrayList<>();

            for (int p = 0; p < 8; p++) {
                List<String> list = new ArrayList<>();
                String formatted = String.format("%03d", p+j);
                String regex = String.format("%s.%s", filename,formatted);
                files = dir.listFiles((dir1, name) -> {
                    return name.matches(regex);
                });

                if (files != null) {
                    for (File file : files) {

                        List<String> fileData = readFileSkippingFirstThreeLines(file);
                        list.addAll(fileData);
                    }
                }else {
                    throw new IllegalArgumentException("file is null");
                }

                for (String row : list) {
                    String[] parts = row.split("\\s+");
//                    System.out.println(parts[0]);
                    String firstColumn = parts[0];  // 第一列的 ID
//                    System.out.println(firstColumn);
                    for (String targetId : stationNumbers) {
                        if (firstColumn.equals(targetId)) {
                            o3All.add(row); // 找到匹配的行，加入结果
                            break; // 一旦匹配上，就跳出内层循环
                        }
                    }
                }
            }
            Map<String, List<Object>> stations = new HashMap<>();
//            System.out.println(o3All);
            for(String row : o3All){
                String[] parts = row.split("\\s+");
                String stationNumber = parts[0];
                double lon = Double.parseDouble(parts[1]);
                double lat = Double.parseDouble(parts[2]);
                double value = Double.parseDouble(parts[4]);

                if (!stations.containsKey(stationNumber)) {
                    stations.put(stationNumber, new ArrayList<>(Arrays.asList(lon, lat, new ArrayList<Double>())));
                }
                // 获取当前站点信息
                List<Object> stationData = stations.get(stationNumber);
                List<Double> forecastResults = (List<Double>) stationData.get(2);
                forecastResults.add(value);

            }
            DecimalFormat df = new DecimalFormat("#.00");

            // 遍历每个站点并输出结果
            for (Map.Entry<String, List<Object>> entry : stations.entrySet()) {
                String stationName = entry.getKey();
                List<Object> stationData = entry.getValue();
                double lon = (double) stationData.get(0);
                double lat = (double) stationData.get(1);
                List<Double> forecastResults = (List<Double>) stationData.get(2);

                // 计算forecastResult的平均值
                double sum = 0;
                for (double result : forecastResults) {
                    sum += result;
                }
                double average = sum / forecastResults.size();

                String output = stationName + " " + df.format(lon) + " " + df.format(lat) + " 0 " + df.format(average);
                resultString.add(output);

            }

            resultString.sort((o1, o2) -> {
                // 提取每一行的站点ID进行比较
                int id1 = Integer.parseInt(o1.split(" ")[0]);
                int id2 = Integer.parseInt(o2.split(" ")[0]);
                return Integer.compare(id1, id2);  // 按照站点ID升序排序
            });
            re.addAll(resultString);
        }

        return extractMaxValues(re);

    }

    // 提取每组最大值对应的行
    public static List<String> extractMaxValues(List<String> data) {
        // 使用一个 Map 存储每个 ID 对应的最大值和对应的行
        Map<String, String> maxValues = new HashMap<>();

        // 遍历所有数据行
        for (String row : data) {
            String[] parts = row.split(" ");
            String id = parts[0];  // 第一列的 ID
            double value = Double.parseDouble(parts[4]);  // 第五列的值

            // 检查该 ID 是否已存在于 map 中
            if (!maxValues.containsKey(id) || value > Double.parseDouble(maxValues.get(id).split(" ")[4])) {
                // 如果不存在或当前值更大，则更新 map 中的记录
                maxValues.put(id, row);
            }
        }
        // 返回所有最大值对应的行
        return new ArrayList<>(maxValues.values());
    }

    // 计算PM25和PM10的日平均预报值
    public static List<String> extractAverageValues(String date, String time,String startTime,String endTime,String city,String element, String filePath) {
        String year = date.substring(0, 4);
        List<String> stationNumbers = getNumbersByCity(city);
        String directoryPath = filePath+"//hour//"+year+"//"+date+"//"+element+"_VALUE";
        List<String> list = new ArrayList<>();
        File dir = new File(directoryPath);
        File[] files = dir.listFiles();
        for(int i = Integer.parseInt(startTime); i <= Integer.parseInt(endTime); i++){
            String formatted = String.format("%03d", i);
            String regex = String.format("%s%s.%s", date, time,formatted);
            System.out.println(regex);
            files = dir.listFiles((dir1, name) -> {
                return name.matches(regex);
            });
            if (files != null) {
                System.out.println("????");
                for (File file : files) {
                    List<String> fileData = readFileSkippingFirstThreeLines(file);
                    list.addAll(fileData);
                }
            }else {
                throw new IllegalArgumentException("file is null");
            }
        }

        List<String> PMAll = new ArrayList<>();

        // 遍历所有数据行
        for (String row : list) {
            String[] parts = row.split("\\s+");
            String firstColumn = parts[0];  // 第一列的 ID
            System.out.println(firstColumn);
            for (String targetId : stationNumbers) {
                if (firstColumn.equals(targetId)) {
                    PMAll.add(row); // 找到匹配的行，加入结果
                    break; // 一旦匹配上，就跳出内层循环
                }
            }
        }
        System.out.println(PMAll);
        Map<String, List<Object>> stations = new HashMap<>();

        for(String row : PMAll){
            String[] parts = row.split("\\s+");
            String stationNumber = parts[0];
            double lon = Double.parseDouble(parts[1]);
            double lat = Double.parseDouble(parts[2]);
            double value = Double.parseDouble(parts[4]);

            if (!stations.containsKey(stationNumber)) {
                stations.put(stationNumber, new ArrayList<>(Arrays.asList(lon, lat, new ArrayList<Double>())));
            }
            // 获取当前站点信息
            List<Object> stationData = stations.get(stationNumber);
            List<Double> forecastResults = (List<Double>) stationData.get(2);
            forecastResults.add(value);

        }
        // 格式化输出
        DecimalFormat df = new DecimalFormat("#.00");
        List<String> resultString = new ArrayList<>();
        // 遍历每个站点并输出结果
        for (Map.Entry<String, List<Object>> entry : stations.entrySet()) {
            String stationName = entry.getKey();
            List<Object> stationData = entry.getValue();
            double lon = (double) stationData.get(0);
            double lat = (double) stationData.get(1);
            List<Double> forecastResults = (List<Double>) stationData.get(2);

            // 计算forecastResult的平均值
            double sum = 0;
            for (double result : forecastResults) {
                sum += result;
            }
            double average = sum / forecastResults.size();

            String output = stationName + " " + df.format(lon) + " " + df.format(lat) + " 0 " + df.format(average);
            resultString.add(output);
        }

        resultString.sort((o1, o2) -> {
            // 提取每一行的站点ID进行比较
            int id1 = Integer.parseInt(o1.split(" ")[0]);
            int id2 = Integer.parseInt(o2.split(" ")[0]);
            return Integer.compare(id1, id2);  // 按照站点ID升序排序
        });

        return resultString;
    }

}
